package com.boot.controller;


import com.boot.entity.R;
import com.boot.entity.Stats;
import com.boot.entity.User;
import com.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户表(User)表控制层
 *
 * @author makejava
 * @since 2023-07-20 18:48:26
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;

    /**
     * 用户登录的业务
     * @return
     */
    @RequestMapping("/login")
    public R login(@RequestParam("username") String username,@RequestParam("password") String password) {
        System.out.println("登录接口：" + username + " " + password);
        User user = userService.queryUserByUsername(username);
        if (user == null)
            return R.fail(401, "用户名不存在！");
        if (!user.getPassword().equals(password)) {
            System.out.println(user);
            return R.fail(402, "密码错误！");
        }
        user.setPassword(null);
        return R.success(user);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @RequestMapping("/insert")
    public R register(User user) {
        userService.save(user);
        return R.success("注册成功！");
    }

    /**
     * 统计用户中男女的比例
     * @return
     */
    @RequestMapping("/queryUserGender")
    public R queryUserGender(){
        List<Stats> list = userService.queryUserGender();
        List<Map> l = new ArrayList<>();

        for (int i =0 ;i<list.size();i++){
            Map map = new HashMap();
            String statsName = list.get(i).getStatsName();
            BigDecimal sum = list.get(i).getSum();
            map.put("name",statsName);
            map.put("value",sum);
            l.add(map);
        }
        return R.success(l);
    }
}

